<?php

namespace app\common\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Order;
use app\admin\model\User;
use app\admin\model\user\Finance;
use app\admin\model\user\Invest;
use app\admin\model\user\Statics;
use app\common\model\Config;
use think\Console;

final class Bonus
{
    private static $id = 0;
    private static $user = null;
    private static $finance = null;
    private static $total = 0.00;

    public function __construct($id, $total)
    {
        self::$id = $id;
        self::$user = User::find($id);
        self::$finance = Finance::where('user_id', self::$id)->find();
        self::$total = $total;

//        self::$user->achievement += self::$total;
//        self::$user->save();

        Config::where('name', 'achievement')->setInc('value', $total);
    }

    /**
     * 添加投资记录
     * @param $orderId
     */
//    public function addInvest($orderId)
//    {
//        $static_bonus_arr = config('site.static_bonus');
//        foreach ($static_bonus_arr as $key => $val) {
//            if (self::$user->level >= $key) {
//                $rate = $val * 0.01;
//            }
//        }
//
//        $idata = [
//            'user_id' => self::$id,
//            'order_id' => $orderId,
//            'money' => self::$total,
//            'days' => 0,
//            'rate' => $rate,
//            'status' => 0
//        ];
//
//        $res = Invest::create($idata);
//    }

    /**
     * 每日静态收益
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusStatic()
    {
        self::bonusShare(self::$total, 5, self::$id);
    }

    /**
     * 获取真实额度
     * @param $tid
     * @param $money
     * @return float|int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBonus($tid, $money)
    {
        $oInfo = \app\admin\model\user\Order::where('user_id', $tid)->where('status', 3)->find();
        if (!$oInfo) {
            return 0;
        }
        $top_multiple = config('site.top_multiple');
        $top_money = $top_multiple * $oInfo->give_money;

        if ($oInfo->profile_money >= $top_money) {
            $oInfo->total_money = 0;
            $oInfo->status = 5;
            $oInfo->save();

            Invest::where('order_id', $oInfo->id)->setField('status', 5);
            return 0;
        } elseif (($oInfo->profile_money + $money) >= $top_money) {
            $bonusmoney = $top_money - $oInfo->profile_money;

            $oInfo->status = 5;
            $oInfo->save();

            Invest::where('order_id', $oInfo->id)->setField('status', 5);
        } else {
            $bonusmoney = $money;
        }

        $oInfo->profile_money += $bonusmoney;
        $oInfo->total_money -= $bonusmoney;
        $oInfo->save();

        return $bonusmoney;
    }

    /**
     * 推荐奖
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusRecom()
    {
        $tinfo = User::field('id,rank,tuijianid')->where('id', self::$user['tuijianid'])->where('status', 'normal')->find();
        if (!$tinfo) {
            return false;
        }

        $recomMoney = self::$total * config('site.recom_rate') * 0.01;
        $recomMoney = $this->getBonus($tinfo['id'], $recomMoney);
        if ($recomMoney > 0) {
            self::bonusShare($recomMoney, 1, $tinfo['id']);
        }

    }

    /**
     * 级差奖(字段为rank)
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusRank()
    {
        $tuijianids = trim(self::$user['tuijianids'], ',');
        //        $rank = 0;
        $rank = self::$user['rank'];
        $tinfos = User::where('id', 'in', $tuijianids)->where('status', 'normal')->where('rank', '>', $rank)->order('tdeep', 'desc')->select();
        if (!$tinfos) {
            return false;
        }

        $team_rate_arr = config('site.team_rate');
        foreach ($tinfos as $val) {
            if ($val['rank'] > $rank) {
                if ($rank == 0) {
                    $rate = $team_rate_arr[$val['rank']] * 0.01;
                } else {
                    $rate = ($team_rate_arr[$val['rank']] - $team_rate_arr[$rank]) * 0.01;
                }

                $leaderMoney = self::$total * $rate;
                $leaderMoney = $this->getBonus($val['id'], $leaderMoney);
//                    var_dump($leaderMoney);die;
                if ($leaderMoney > 0) {
                    self::bonusShare($leaderMoney, 2, $val['id']);
                    if ($val['rank'] >= 3) {
                        self::bonusPing($val['id'], $leaderMoney);
                    }
                }

                $rank = $val['rank'];
            }
        }
    }

    /**
     * 平级奖
     * @param $tid
     * @param $leaderMoney
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusPing($tid, $leaderMoney)
    {
        $info = User::find($tid);
        $tuijianids = trim($info['tuijianids'], ',');
        $tinfos = User::where('id', 'in', $tuijianids)
            ->where('status', 'normal')
            ->where('rank', '>=', $info['rank'])
            ->order('tdeep', 'desc')->select();
        if (!$tinfos) {
            return false;
        }

        $pingRate = config('site.ping_rate') * 0.01;
        $pingMoney = $leaderMoney * $pingRate;
        if (!$pingMoney) {
            return false;
        }
        foreach ($tinfos as $val) {
            if ($val['rank'] == $info['rank']) {
                $pingMoney = $this->getBonus($val['id'], $pingMoney);
                if ($pingMoney > 0) {
                    self::bonusShare($pingMoney, 4, $val['id']);
                }
                break;
            } elseif ($val['rank'] > $info['rank']) {
                break;
            }
        }
    }

    /**
     * 添加业绩
     * @return bool
     * @throws \think\Exception
     */
    public function addAchievement()
    {
        if (!self::$user->tuijianid) {
            return false;
        }

        $map = [
            'id' => ['in', trim(self::$user->tuijianids, ',')],
            'status' => 'normal',
        ];

        User::where($map)->setInc('achievement', self::$total);
    }

    /**
     * 会员级别更新
     */
    public function bonusUpdate1()
    {
        $team_update_condition1 = config('site.team_update_condition');
        $team_update_condition2 = config('site.team_update_condition2');
        $keys = array_keys($team_update_condition1);
        $max = end($keys);
        $nteam_update_condition = [];
        foreach ($team_update_condition1 as $k1 => $v1) {
            $item = [
                'rank' => $k1,
                'achievement' => $team_update_condition2[$k1],
                'value' => $v1
            ];
            $nteam_update_condition[] = $item;
        }

        $tuijianids = trim(self::$user['tuijianids'], ',');
        $tinfos = User::where('id', 'in', $tuijianids)->where('status', 'normal')->order('tdeep', 'desc')->select();

        if (!$tinfos) {
            return false;
        }

        foreach ($tinfos as $val) {
            if ($val['rank'] >= $max) {
                continue;
            }

            $sons = User::where('tuijianid', $val['id'])->where('status', 'normal')->select();
            foreach ($nteam_update_condition as $v1) {
                if ($val['rank'] < $v1['rank']) {
                    if (count($sons) < $v1['value']) {
                        break;
                    }
                }

                if ($val['achievement'] < $v1['achievement']) {
                    break;
                }

                $num = 0;
                foreach ($sons as $v2) {
                    if ($v2['rank'] >= $val['rank']) {
                        $num += 1;
                        continue;
                    }
                    $count = User::where('tuijianids', 'like', '%,' . $v2['id'] . ',%')->where('rank', '>=', $val['rank'])->count();
                    if ($count >= 1) {
                        $num += 1;
                    }
                }

                if ($num >= $v1['value']) {
                    User::where('id', $val['id'])->setField('rank', $v1['rank']);
                }
            }
        }
    }

    /**
     * 已弃用
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bonusUpdate2()
    {
        $static_level_condition = config('site.static_level');
        $keys = array_keys($static_level_condition);
        $max = end($keys);
        $nteam_update_condition = [];
        foreach ($static_level_condition as $k1 => $v1) {
            $item = [
                'level' => $k1,
                'value' => $v1
            ];
            $nteam_update_condition[] = $item;
        }

        $tuijianids = trim(self::$user['tuijianids'], ',');
        $tinfos = User::where('id', 'in', $tuijianids)->where('status', 'normal')->order('tdeep', 'desc')->select();
        if (!$tinfos) {
            return false;
        }

        foreach ($tinfos as $val) {
            if ($val['level'] >= $max) {
                continue;
            }

            $sons = User::where('tuijianid', $val['id'])->where('status', 'normal')->select();
            foreach ($nteam_update_condition as $v1) {
                if ($val['level'] < $v1['level']) {
                    if (count($sons) < $v1['value']) {
                        break;
                    }
                }

                $num = 0;
                foreach ($sons as $v2) {
                    if ($v2['level'] >= $val['level']) {
                        $num += 1;
                        continue;
                    }
                    $count = User::where('tuijianids', 'like', '%,' . $v2['id'] . ',%')->where('level', '>=', $val['level'])->count();
                    if ($count >= 1) {
                        $num += 1;
                    }
                }

                if ($num >= $v1['value']) {
                    User::where('id', $val['id'])->setField('level', $v1['level']);
                }
            }
        }
    }

    /**
     * 奖金生成
     * @param $bonusmoney
     * @param $change_type
     * @param $id
     * @param $fromuser
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusShare($bonusmoney, $change_type, $tid)
    {
        $tax_rate = config('site.tax_rate');
        if ($tax_rate > 100 || $tax_rate <= 0) {
            $tax = 0;
        } else {
            $tax = $tax_rate * 0.01;
        }

        $tax_money = $bonusmoney * $tax;
        $actulMoney = round($bonusmoney - $tax_money, 2);

        $user = User::find($tid);
        if ($user->money_rate > 0 || $user->shop_rate > 0) {
            $money_rate = $user->money_rate;
            $shop_rate = $user->shop_rate;
        } else {
            $money_rate = config('site.money_rate');
            $shop_rate = config('site.shop_rate');
        }

        $hasmoney = round($actulMoney * $money_rate * 0.01, 2);
        $shopmoney = round($actulMoney * $shop_rate * 0.01, 2);

        self::$finance->hasmoney += $hasmoney;
        self::$finance->allmoney += $hasmoney;
        self::$finance->hasshop += $shopmoney;
        self::$finance->allshop += $shopmoney;

        self::$finance->allbonus += $bonusmoney;
        $res = self::$finance->save();
        if ($res) {
            self::bonus('bonus_day', $change_type, $tid, $bonusmoney, $actulMoney);
            self::bonus('bonus_total', $change_type, $tid, $bonusmoney, $actulMoney);

            $orderNum = create_order($tid);
            $mdata1 = [
                'order_num' => $orderNum,
                'record_type' => 1,
                'change_type' => $change_type,
                'moneytype' => 2,
                'money' => $hasmoney,
                'hasmoney' => self::$finance->hasmoney,
//                'remark' => $tag,
                'user_id' => self::$id,
                'targetuserid' => $tid
            ];
            Change::create($mdata1);

            if ($shopmoney > 0) {
                $orderNum = create_order($tid);
                $mdat2 = [
                    'order_num' => $orderNum,
                    'record_type' => 1,
                    'change_type' => $change_type,
                    'moneytype' => 3,
                    'money' => $shopmoney,
                    'hasmoney' => self::$finance->hasshop,
//                'remark' => $tag,
                    'user_id' => self::$id,
                    'targetuserid' => $tid
                ];

                Change::create($mdat2);
            }
        }
    }

    /**
     * @param $table
     * @param $bonustype
     * @param $touser
     * @param $money
     * @param $hasmoney
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function bonus($table, $bonustype, $touid, $money, $hasmoney)
    {
        $touser = User::find($touid);
        if ($table == 'bonus_day') {
            $count_date = strtotime('today');
            $map['count_date'] = $count_date;
        } else {
            $count_date = time();
        }

        $BCount = Db($table);
        $map['user_id'] = $touid;
        $bonusData = $BCount->where($map)->find();
        $field = 'bonus' . $bonustype;
        if ($bonusData) {
            $data[$field] = $bonusData[$field] + $money;
            $data['total'] = $bonusData['total'] + $hasmoney;
            $data['tax_money'] = round($money - $hasmoney, 2);
            $BCount->where($map)->update($data);
        } else {
            $data = array(
                'user_id' => $touser['id'],
                'count_date' => $count_date
            );
            $data[$field] = $money;
            $data['total'] = $hasmoney;
            $data['tax_money'] = round($money - $hasmoney, 2);
            $BCount->insert($data);
        }
    }
}